package com.ym521.emojipack;

import android.text.style.DynamicDrawableSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.LayoutInflaterCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import com.ym521.emojipack.emoji.EmojiPack;
import com.ym521.emojipack.install.EmojiPackLayoutInflaterFactory;
import com.ym521.emojipack.install.EmojiPackTextWatcher;

/**
 * @author Ym
 * E-mail: 2435970206@qq.com
 * createTime:2023/7/9
 * explain: emoji 一次设置
 * 不在需要替换将控件xx成 EmojiPackxx
 */
public final class EmojiPackHelper {

    public static Builder activity(AppCompatActivity activity) {
        return new Builder(activity);
    }

    public static Builder view(View view) {
        return new Builder(view);
    }

    public static final class Builder {
        //emoji 放大常数
        public static final float EMOJI_ENLARGE = 1.2f;
        public AppCompatActivity activity;
        @EmojiPack.Alignment
        public int alignment = DynamicDrawableSpan.ALIGN_BASELINE;
        private boolean gone = false;
        private View view;

        public Builder(@NonNull AppCompatActivity activity) {
            this.activity = activity;
        }

        public Builder(@NonNull View view) {
            if (view == null) {
                throw new IllegalArgumentException("The given view must not be null");
            }
            this.view = view;
        }

        public Builder alignment(@EmojiPack.Alignment int alignment) {
            checkGone();
            this.alignment = alignment;
            return this;
        }

        public void install() {
            checkGone();
            if (activity != null) {
                LayoutInflaterCompat.setFactory2(activity.getLayoutInflater(),
                        new EmojiPackLayoutInflaterFactory(this));
            } else {
                emojiSize(view);
            }
            gone = true;
        }

        private void emojiSize(View view) {
            if (view instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) view;
                for (int index = 0; index < viewGroup.getChildCount(); index++) {
                    emojiSize(viewGroup.getChildAt(index));
                }
            } else if (view instanceof TextView) {
                TextView textView = (TextView) view;
                textView.addTextChangedListener(new EmojiPackTextWatcher(textView, this));
            }
        }

        void checkGone() {
            if (gone) {
                throw new IllegalStateException("Sorry, it's already gone");
            }
        }
    }
}
